package org.fin.minicat.container;

import org.fin.minicat.request.Request;
import org.fin.minicat.responce.Responce;
import org.fin.minicat.startup.Connector;

import java.awt.*;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class Service {

  private Engine engine;

  private final Executor executor;

  private List<Connector> connectors;

  public Service() {
    executor = Executors.newCachedThreadPool();
    connectors = new LinkedList<>();
  }

  public void process(Request request, Responce responce) throws Exception {
    engine.process(request, responce);
  }

  public void start() {
    CyclicBarrier cyclicBarrier = new CyclicBarrier(connectors.size());

    for (Connector connector : connectors) {
      connector.setCyclicBarrier(cyclicBarrier);
      new Thread(connector::start).start();
    }
  }

  /**
   * 向Service添加一个Connector
   * @param connector   一个Connector
   */
  public void addConnector(Connector connector) {
    connectors.add(connector);
  }

  public Engine getEngine() {
    return engine;
  }

  public void setEngine(Engine engine) {
    this.engine = engine;
  }

  public Executor getExecutor() {
    return executor;
  }
}
